from _decimal import Decimal

from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from goods.models import SKU
from rest_framework.generics import CreateAPIView
# from rest_framework.permissions import IsAuthenticated

# Create your views here.
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer


class OrderSettlementView(APIView):
    """订单结算"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user

        # 从购物车勾选 用户要结算的商品
        conn = get_redis_connection('cart')
        cart_hash = conn.hgetall('cart_%s' % user.id)
        cart_selected = conn.smembers('cart_select_%s' % user.id)
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(cart_hash[sku_id])

        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')
        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})
        return Response(serializer.data)


class SaveOrderView(CreateAPIView):
    serializer_class = SaveOrderSerializer
    permission_classes = [IsAuthenticated]
